﻿using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.Json;
using Lihong.Cms.Data;
using Lihong.Cms.Entity;
using Microsoft.AspNetCore.Mvc;

namespace Lihong.Cms.Web.Controllers
{
    public class UserController : Controller
    {
        //User u = new User()
        //{
        //    Id = 1,
        //    Avator = "/img/1.jpg",
        //    CreatedOn = DateTime.Now,
        //    NickName = "长胖的小胖子",
        //    Email = "lihong@gzbit.com",
        //    Phone = "131 1234 1234",
        //    UserName = "lihong"
        //};

        const string USERFILE = "Data\\user.json";

        // json序列化 / json反序列化  json/xml

        public IActionResult Index()
        {
            User u = new User();
            if (System.IO.File.Exists(USERFILE)) //先判断文件是否存在，存在才读取
            {
                string s = System.IO.File.ReadAllText(USERFILE, Encoding.UTF8);
                if (s != null && s != string.Empty)
                {
                    try   //异常处理
                    {
                        u = JsonSerializer.Deserialize<User>(s);
                    }
                    catch (Exception ex)
                    {
                        System.IO.File.AppendAllText("Data\\Error.txt", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " >> JSON反序列化出错"
                            + Environment.NewLine + ex.Message
                            + Environment.NewLine + ex.ToString()
                            + Environment.NewLine);
                    }
                    finally
                    {
                        Console.WriteLine("一定会被执行");
                    }
                }
            }
            return View(u);
        }

        public IActionResult Save(User user)
        {

            User e = new User();

            string s = JsonSerializer.Serialize(user);
            Directory.CreateDirectory("Data");
            System.IO.File.WriteAllText(USERFILE, s, Encoding.UTF8);
            return View();
        }
    }
}
